package top.lemos.navib;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;

import java.util.ArrayList;
import java.util.List;

import overlay.RouteOverlay;
import overlay.WalkRouteOverlay;

/**
 * Created by Sonp on 2017/5/6.
 */

public class ShowActivity extends Activity {
    public static final String EXTRA_IS_ELEVATOR_USED = "is_elevator_used";
    public static final String EXTRA_BUILDING_NUM = "building_num";
    public static final String EXTRA_CLASSROOM_NUM = "classroom_num";
    public static final String ROUTEINDEX = "route_index";
    public static final String INFO = "mInfos";
    public static final String PIC = "mPics";
    private String mBuidingNum;
    private String mClassroomNum;
    private Boolean mElevatorUsed;
    private ImageView mBackButton;
    private ImageView mNextButton;
    private ImageView mPrevButton;
    private TextView mTitleText;
    private TextView mInfoText;
    private ImageView mPicView;
    private int mIndex = 0;
    private ArrayList<String> mInfos;
    private ArrayList<String> mPics;

    private MapView mMapView;
    private CheckBox mMapButton;
    private Boolean mOpenMap = false;
    AMapLocationClient mLocationClient;



    private LatLonPoint mStartPoint = null;
    private AMap aMap;
    final private LatLonPoint mEndPoint = new LatLonPoint(34.126059, 108.831978);
    private static final int PERMISSON_REQUESTCODE = 0;
    private ProgressDialog progDialog = null;
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    private Integer getPicId(String picName) {
        try {
            String fileName = picName.substring(0, picName.lastIndexOf("."));
            return R.drawable.class.getField(fileName).getInt(null);
        } catch (Exception e) {
            new AlertDialog.Builder(this).setMessage("图片加载失败").
                    setPositiveButton("确定", null).
                    show();
            return R.drawable.test;
        }
    }

    private void update() {
        if (mOpenMap) {
            mPicView.setVisibility(View.GONE);
            mMapView.setVisibility(View.VISIBLE);

        } else {
            mPicView.setVisibility(View.VISIBLE);
            mMapView.setVisibility(View.GONE);

            Integer picId = getPicId(mPics.get(mIndex));
            mPicView.setImageResource(picId);
            mPicView.setTag(picId);
        }
        mInfoText.setText(mInfos.get(mIndex));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBuidingNum = getIntent().getStringExtra(EXTRA_BUILDING_NUM);
        mClassroomNum = getIntent().getStringExtra(EXTRA_CLASSROOM_NUM);
        mElevatorUsed = getIntent().getBooleanExtra(EXTRA_IS_ELEVATOR_USED, true);

        setContentView(R.layout.activity_show);

        if (savedInstanceState != null) {
            mIndex = savedInstanceState.getInt(ROUTEINDEX);
            mInfos = savedInstanceState.getStringArrayList(INFO);
            mPics = savedInstanceState.getStringArrayList(PIC);
        } else {
            Nav.GetInstance().SetElevator(mElevatorUsed);
            Nav.GetInstance().Router(mBuidingNum, mClassroomNum);
            mInfos = (ArrayList) Nav.GetInstance().GetRoute();
            mPics = (ArrayList) Nav.GetInstance().GetPhoto();
        }

        mTitleText = (TextView) findViewById(R.id.show_title_text);
        mTitleText.setText(mBuidingNum + "——>" + mClassroomNum);
        mInfoText = (TextView) findViewById(R.id.info_text);
        mPicView = (ImageView) findViewById(R.id.show_image);
        mPicView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getFragmentManager();
                PictureFragment.newInstance((Integer) mPicView.getTag()).show(fm, null);
            }
        });
        mBackButton = (ImageView) findViewById(R.id.back_button_image);
        mBackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mNextButton = (ImageView) findViewById(R.id.next_button_image);
        mNextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIndex++;
                if (mIndex < mInfos.size()) update();
                else {
                    mIndex--;
                    Toast.makeText(getApplicationContext(), R.string.nonext, Toast.LENGTH_SHORT).show();
                }
            }
        });
        mPrevButton = (ImageView) findViewById(R.id.prev_button_image);
        mPrevButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIndex--;
                if (mIndex >= 0) update();
                else {
                    mIndex++;
                    Toast.makeText(getApplicationContext(), R.string.noprev, Toast.LENGTH_SHORT).show();
                }
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) checkPermissions();
        mapDisplay(savedInstanceState);
        locate();
        update();
    }


    void mapInit(){
        if (aMap == null) {
            aMap = mMapView.getMap();
            aMap.getUiSettings().setMyLocationButtonEnabled(true);
            aMap.getUiSettings().setCompassEnabled(true);
            aMap.getUiSettings().setScaleControlsEnabled(true);
            aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
            MyLocationStyle myLocationStyle = new MyLocationStyle();
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
            aMap.setMyLocationStyle(myLocationStyle);
            aMap.setMyLocationEnabled(true);
        }
    }

    private void mapDisplay(Bundle savedInstanceState) {
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        mapInit();
        mMapButton = (CheckBox) findViewById(R.id.map_button);
        mMapButton.setChecked(mOpenMap);
        mMapButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                debug(true);
                mOpenMap = isChecked;
                update();
            }
        });
    }

    @TargetApi(value = Build.VERSION_CODES.M)
    private void checkPermissions() {
        List<String> denyPermssions = new ArrayList<String>();
        for (String perm : needPermissions) {
            if (ContextCompat.checkSelfPermission(this, perm)
                    != PackageManager.PERMISSION_GRANTED) {
                denyPermssions.add(perm);
            }
        }
        if (!denyPermssions.isEmpty())
            ActivityCompat.requestPermissions(this,
                    denyPermssions.toArray(new String[denyPermssions.size()]), PERMISSON_REQUESTCODE);
    }


    private void locate() {
        AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation mAMapLocation) {
                mStartPoint = new LatLonPoint(mAMapLocation.getLatitude(), mAMapLocation.getLongitude());
                route();
            }
        };

       mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mAMapLocationListener);
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    private void route() {
       RouteSearch.OnRouteSearchListener mOnRouteSearchListener = new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult mBusRouteResult, int mI) {
            }

            @Override
            public void onDriveRouteSearched(DriveRouteResult mDriveRouteResult, int mI) {

            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {
                dissmissProgressDialog();
                if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (result != null && result.getPaths() != null) {
                        if (result.getPaths().size() > 0) {
                            WalkRouteResult mWalkRouteResult = result;
                            final WalkPath walkPath = mWalkRouteResult.getPaths().get(0);
                            WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(
                                    getApplication(), aMap, walkPath,
                                    mWalkRouteResult.getStartPos(),
                                    mWalkRouteResult.getTargetPos());
                            walkRouteOverlay.removeFromMap();
                            walkRouteOverlay.addToMap();
                            walkRouteOverlay.zoomToSpan();
                            setfromandtoMarker();
                            debug(true);
                        }
                    }
                }
            }

            @Override
            public void onRideRouteSearched(RideRouteResult mRideRouteResult, int mI) {

            }
        };

        RouteSearch mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(mOnRouteSearchListener);
        if (mStartPoint == null) return;
        showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);
            RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo);
            mRouteSearch.calculateWalkRouteAsyn(query);
    }


    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(true);
        progDialog.setMessage("正在搜索");
        progDialog.show();
    }

    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    private void debug(boolean mB){
       if (mB||aMap.getMyLocationStyle().getMyLocationType() != MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE)
            aMap.setMyLocationStyle(new MyLocationStyle().myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE));
    }

    private void setfromandtoMarker() {
        aMap.addMarker(new MarkerOptions()
                .position(RouteOverlay.convertToLatLng(mStartPoint))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.start)));
        aMap.addMarker(new MarkerOptions()
                .position(RouteOverlay.convertToLatLng(mEndPoint)).title("B楼")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));
    }

    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt(ROUTEINDEX, mIndex);
        savedInstanceState.putStringArrayList(INFO, mInfos);
        savedInstanceState.putStringArrayList(PIC, mPics);

        if (savedInstanceState != null)
            mMapView.onSaveInstanceState(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mLocationClient.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.stopLocation();
    }

    @TargetApi(value = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED &&
                        ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                    AlertDialog dialog = new AlertDialog.Builder(this)
                            .setMessage("该应用需要此权限，不开启将无法正常工作！")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            }).create();
                    dialog.show();
                }
            }
        }
    }

}
